﻿using CXW.Core.Sharp.Gui;
using System;

namespace CXW.Core.Sharp
{
    public class WorkbenchSingleton
    {
        static WorkBenchWindow _workbench;
        public static WorkBenchWindow Workbench { get { return _workbench; } }

        /// <summary>
        /// Throws an exception if the current thread is not the main thread.
        /// </summary>
        public static void AssertMainThread()
        {
            if (InvokeRequired)
            {
                throw new InvalidOperationException("This operation can be called on the main thread only.");
            }
        }

        public static bool InvokeRequired
        {
            get
            {
                if (_workbench == null)
                    return false; // unit test mode, don't crash
                else
                    return _workbench.InvokeRequired;
            }
        }
        public static void InitializeWorkbench(WorkBenchWindow workbench)
        {
            _workbench = workbench;
            //var messageService = Core.Services.ServiceManager.Instance.MessageService as IDialogMessageService;
            //if (messageService != null) { messageService.DialogOwner = workbench; }
            _workbench.Initialize();
            _workbench.SetMemento(PropertyService.Get("Workbench", new Properties()));
            _workbench.SetDockPanelVisabled(PropertyService.Get("DockPanel", new Properties()));
        }

        /// <summary>
        /// Makes a call GUI threadsafe. WARNING: This method waits for the result of the
        /// operation, which can result in a dead-lock when the main thread waits for a lock
        /// held by this thread!
        /// </summary>
        public static R SafeThreadFunction<A, R>(Func<A, R> method, A arg1)
        {
            if (_workbench.InvokeRequired)
                return (R)_workbench.Invoke(method, new object[] { arg1 });
            else
                return method(arg1);
        }
    }
}
